import { BadRequestException, Inject, Injectable } from '@nestjs/common';

import { RegisterUserDto } from './dto/register-user.dto';
import { DbService } from 'src/db/db.service';
import { User } from './entities/user.entity';
import { LoginUserDto } from './dto/login-user.dto';

@Injectable()
export class UserService {
  @Inject(DbService)
  private dbService: DbService;
  async register(registerDto: RegisterUserDto) {
    const { username = '', password = '' } = registerDto;
    const users: User[] = await this.dbService.read();
    const foundUser = users.find((v) => {
      return v.username === username;
    });
    if (foundUser) {
      throw new BadRequestException('该用户已存在');
    }
    const user = new User();
    user.username = username;
    user.password = password;
    users.push(user);
    await this.dbService.write(users);
    return user;
  }
  async login(loginDto: LoginUserDto) {
    const { username = '', password = '' } = loginDto;
    const users: User[] = await this.dbService.read();
    const foundUser = users.find((v) => {
      return v.username === username;
    });
    if (!foundUser) {
      throw new BadRequestException('该用户不存在');
    }
    if (foundUser.password !== password) {
      throw new BadRequestException('密码错误');
    }
    return {
      user: foundUser,
      token: '12321312',
      message: '登录成功',
    };
  }
}
